'use strict';

// Content script file will run in the context of web page.
// With content script you can manipulate the web pages using
// Document Object Model (DOM).
// You can also pass information to the parent extension.

// We execute this script by making an entry in manifest.json file
// under `content_scripts` property

// For more information on Content Scripts,
// See https://developer.chrome.com/extensions/content_scripts

import Stats from './stats.js';

let stats = new Stats();
stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom

// 时间刻度，只需要记录1秒的帧率
let beginTime = (performance || Date).now(), prevTime = beginTime;

// 获取Title
let title = document.getElementsByTagName('title')[0].innerText;

function animate() {
  stats.begin();

  // 返回帧率信息
  let time = (performance || Date).now();
  if (time >= prevTime + 1000) {
    prevTime = time;
    chrome.runtime.sendMessage(
      {
        type: 'FPS',
        payload: {
          time: new Date().toTimeString().split(' ')[0],
          currFPS: stats.currVal().currFPS,
          currMEM: stats.currVal().currMEM,
          title: title
        }
      }
    );
  }

  stats.end();
  chrome.storage.local.get({ running: 0 }, item => {
    if (item.running === 1) {
      requestAnimationFrame(animate);
    }
  })
}


// Listen for message
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'START') {
    document.body.appendChild(stats.dom);
    requestAnimationFrame(animate);
  }

  if (request.type === 'STOP') {
    document.body.removeChild(stats.dom);
  }

  // Send an empty response
  // See https://github.com/mozilla/webextension-polyfill/issues/130#issuecomment-531531890
  sendResponse({});
  return true;
});




